// eslint-disable-next-line
import { BasicLayout, BlankLayout, PageView, RouteView } from '@/layouts'
import * as loginService from '@/api/login'
import storage from 'store'
import { APP_USER, ENABLE_TOKEN } from '@/store/mutation-types'
import Wf_MyTaskUndoOperation from '../views/workflow/Wf_MyTaskUndoOperation.vue'
import { iconMap } from '@/core/icons'

// 前端未找到页面路由（固定不用改）
const notFoundRouter = {
  path: '*',
  redirect: '/404',
  hidden: true
}

// 中转页面
const ssoBack = {
  path: '/ssoback',
  name: 'ssoback',
  component: () => import('@/views/Ssoback'),
  hidden: true
}

// 根级菜单
const rootRouter = {
  name: 'root',
  path: '/',
  component: BasicLayout,
  redirect: '/home',
  meta: {
    title: '首页'
  },
  children: [
    {
      path: '/Wf_MyTaskUndoOperation/:taskid/:pattern',
      component: Wf_MyTaskUndoOperation
    }
  ]
}

/**
 * 动态生成菜单
 * @param token
 * @returns {Promise<Router>}
 */
export const generatorDynamicRouter = token => {
  return new Promise((resolve, reject) => {
    const user = storage.get(APP_USER)

    if (!token && !user) {
      return
    }
    // let param = {}
    // if (!ENABLE_TOKEN) { // 当所在环境为测试环境时，通过当前人id获取菜单，否则通过token获取
    //   param = {
    //     userId: user.userId
    //   }
    // }

    const param = {}
    loginService
      .getCurrentUserMenu(param)
      .then(res => {
        console.log('接口路由菜单', res)
        let { data } = res
        data = data.sort((a, b) => a.seqnum - b.seqnum)
        // 进行排序
        rootRouter.children = []

        const routers = []
        const user_routers = generator(data)
        rootRouter.children = user_routers
        rootRouter.children.push({
          path: '/ha_modifyInfo',
          name: 'ha_modifyInfo',
          component: () => import('@/views/base/Ha_modifyInfo.vue'),
          hidden: true
        })
        rootRouter.children.push({
          path: '/home',
          name: 'home',
          component: () => import('@/views/Home'),
          meta: {
            title: '首页',
            icon: 'appstore'
          },
          hidden: true
        })
        routers.push(rootRouter)
        routers.push(notFoundRouter)
        routers.push(ssoBack)
        resolve(routers)
      })
      .catch(err => {
        reject(err)
      })
    console.log('配置路由菜单', rootRouter)
  })
}

/**
 * 格式化树形结构数据 生成 vue-router 层级路由表
 *
 * @param routerMap
 * @param parent
 * @returns {*}
 */
export const generator = (routerMap, parent) => {
  return routerMap.map(item => {
    // console.log(iconMap, iconMap[item.icon])
    // const { title, show, hideChildren, hiddenHeaderContent, target, icon } = item.meta || {}
    var currentRouter = {
      // 如果路由设置了 path，则作为默认 path，否则 路由地址 动态拼接生成如 /dashboard/workplace
      path: item.path || '',
      // 路由名称，建议唯一
      name: item.name || '',
      // 该路由对应页面的 组件 :方案1
      // component: constantRouterComponents[item.component || item.key],
      // 该路由对应页面的 组件 :方案2 (动态加载)
      component: !item.component ? RouteView : () => import(`@/views/${item.component}`),

      // meta: 页面标题, 菜单图标, 页面权限(供指令权限用，可去掉)
      meta: {
        title: item.description,
        icon: iconMap[item.icon] || undefined,
        hidden: item.routetype === 1 ? true : false || true
      }
    }

    if (item.hide && item.hide === 1) {
      currentRouter.hidden = true
    }

    if (item.redirect) {
      currentRouter.redirect = item.redirect
    }
    if (item.component) {
      currentRouter.component = () => import(`@/views/${item.component}`)
    }
    // 没有重定向地址也没有vue组件默认为外链
    if (!item.redirect && !item.component) {
      currentRouter.meta.target = '_blank'
    }

    let hide = false
    if (item.children) {
      let count = 0
      item.children.forEach(child => {
        if (child.routetype === 1) {
          count++
        }
      })
      if (count === item.children.length) {
        hide = true
      }
    }

    // 是否设置了隐藏子菜单
    if (hide) {
      currentRouter.hideChildrenInMenu = true
    }
    // 为了防止出现后端返回结果不规范，处理有可能出现拼接出两个 反斜杠
    if (!currentRouter.path.startsWith('http')) {
      currentRouter.path = currentRouter.path.replace('//', '/')
    }
    // 重定向
    // item.redirect && (currentRouter.redirect = item.redirect)
    // 是否有子菜单，并递归处理
    if (item.children && item.children.length > 0) {
      // Recursion
      currentRouter.children = generator(item.children, currentRouter)
    }
    return currentRouter
  })
}
